package com.ruyuan.commodity.consumer.core.consumer.goods;

import cn.hutool.json.JSONUtil;
import com.ruyuan.commodity.consumer.api.GoodsFeignClient;
import com.ruyuan.commodity.model.goods.vo.CacheGoods;
import com.ruyuan.commodity.model.goods.vo.GoodsSkuVO;
import com.ruyuan.commodity.open.api.client.shiptemplate.ShipTemplateOpenApi;
import com.ruyuan.commodity.open.api.model.base.CachePrefix;
import com.ruyuan.commodity.open.api.model.base.message.GoodsChangeMsg;
import com.ruyuan.commodity.consumer.core.event.GoodsChangeEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.List;

/**
 * 商品变化的时候对运费模板的copy操作
 */
@Service
public class GoodsChangeTemplateConsumer implements GoodsChangeEvent {

    private static final Logger LOG = LoggerFactory.getLogger(GoodsChangeTemplateConsumer.class);

    /**
     * 商品的feign client
     */
    @Autowired
    private GoodsFeignClient goodsFeignClient;
    /**
     * redis操作模板
     */
    @Autowired
    private RedisTemplate<String, String> cache;
    /**
     * 运费模板的open api
     */
    @Autowired
    private ShipTemplateOpenApi shipTemplateOpenApi;

    @Override
    public void goodsChange(GoodsChangeMsg goodsChangeMsg) {
        LOG.info("进入商品更新后 copy运费模板的逻辑 入参为 [{}]", JSONUtil.toJsonStr(goodsChangeMsg));
        // 如果是进行添加或者修修改商品操作，需要将sku和模板进行绑定
        if (goodsChangeMsg.getOperationType() == GoodsChangeMsg.ADD_OPERATION || goodsChangeMsg.getOperationType() == GoodsChangeMsg.UPDATE_OPERATION) {
            // 获取商品id
            Long goodsId = goodsChangeMsg.getGoodsIds()[0];
            // 查询此商品绑定的运费模板
            CacheGoods cacheGoods = goodsFeignClient.getFromCache(goodsId);
            // 如果此商品绑定运费模板的情况下，给sku绑定脚本
            if (cacheGoods.getTemplateId()!=0) {
                // 获取当前商品的信息
                List<GoodsSkuVO> goodsSkuVOList = goodsFeignClient.listByGoodsId(goodsId);
                for (GoodsSkuVO goodsSkuVO : goodsSkuVOList) {
                    List<String> scripts = shipTemplateOpenApi.getScripts(cacheGoods.getTemplateId());
                    goodsSkuVO.setScripts(scripts);
                    goodsSkuVO.setTemplateId(cacheGoods.getTemplateId());
                    // 重新存入缓存
                    cache.opsForValue().set(CachePrefix.SKU.getPrefix() + goodsSkuVO.getSkuId(), JSONUtil.toJsonStr(goodsSkuVO));
                }
            }
        }

    }

}
